<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/main' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>钱包</el-breadcrumb-item>
    </el-breadcrumb>
    <div v-show="emptyShow" class="empty-box">
      <img style="width:25rem" :src="emptyImage" alt />
      <span>You have not registered a wallet account.</span>
      <el-button type="primary" @click="dialogVisible=true">注册</el-button>
    </div>

    <div v-show="mainShow" class="main-box-top">
      <div class="card-div">
        <div class="bank-card">
          <span class="account">账户: {{name}}</span>
          <span class="account">可用金额: ${{money}}</span>
        </div>
        <br />
        <div class="btn-div">
          <el-popover placement="right" width="380" v-model="visible1">
            <div class="password">
              <el-input
                style="width:300px"
                v-model="password"
                placeholder="请输入你的密码."
                prefix-icon="el-icon-lock"
                show-password
              ></el-input>
              <el-button type="primary" size="small" @click="WithdrawPass">确定</el-button>
            </div>
            <el-button style="width:10rem" type="primary" slot="reference" round plain>提现</el-button>
          </el-popover>

          <el-popover placement="right" width="380" v-model="visible">
            <div class="password">
              <el-input
                style="width:300px"
                v-model="password"
                placeholder="请输入你的钱包密码."
                prefix-icon="el-icon-lock"
                show-password
              ></el-input>
              <el-button type="primary" size="small" @click="AccountPass">确定</el-button>
            </div>
            <el-button style="width:10rem" type="primary" slot="reference" round plain>账户管理</el-button>
          </el-popover>
        </div>
      </div>

      <div class="main-box-top">
        <el-link style="font-size:18px" :underline="false" type="success">提现记录</el-link>
        <el-divider></el-divider>
        <span>记录项：</span>
        <el-date-picker
          v-model="time"
          @change="search"
          type="daterange"
          unlink-panels
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>

        <el-table size="medium" :data="tableData.slice((currentPage-1)*pagesize,currentPage*pagesize)" style="width: 100%" class="table" height="220">
          <el-table-column prop="num" label="事务编号"></el-table-column>
          <el-table-column prop="amount" label="账户"></el-table-column>
          <el-table-column prop="money" label="金额"></el-table-column>
          <el-table-column prop="time" label="完成时间"></el-table-column>
          <el-table-column prop="state" label="状态">
            <template slot-scope="scope">
              <el-tag disable-transitions>{{scope.row.state}}</el-tag>
            </template>
          </el-table-column>
        </el-table>
          <br>
        <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[3,6,9,tableData.length]"
      :page-size="pagesize"
      layout="total,sizes,prev,pager,next,jumper"
      :total="tableData.length"
    ></el-pagination>
      </div>
    </div>

    <el-dialog title="提现" :visible.sync="dialogWithdraw" width="25%">
      <span>
        提现金额：
        <el-input style="width:200px" v-model="Withdraw_money"></el-input>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogWithdraw = false">删除</el-button>
        <el-button type="primary" @click="Withdraw">确认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="密码管理" :visible.sync="dialogAccount" width="30%">
      <el-form :model="passwordForm" ref="passwordForm" label-width="120px">
        <el-form-item
          label="新密码"
          prop="password"
          :rules="[{ validator: validatePass3, trigger: 'blur' }]"
        >
          <el-input
            style="width:20rem"
            show-password
            v-model="passwordForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item
          label="检查密码"
          prop="checkPass"
          :rules="[{ validator: validatePass4, trigger: 'blur' }]"
        >
          <el-input
            style="width:20rem"
            show-password
            v-model="passwordForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaCancel('passwordForm')">删除</el-button>
        <el-button type="primary" @click="passwordSubForm('passwordForm')">确认</el-button>
      </span>
    </el-dialog>

    <el-dialog title="钱包账户注册" :visible.sync="dialogVisible" width="30%">
      <el-form :model="walletRegForm" ref="walletRegForm" label-width="120px">
        <el-form-item
          label="账户名称"
          prop="name"
          :rules="[{ required: true, message: '请输入你的账户名称'}]"
        >
          <el-input style="width:20rem" v-model="walletRegForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <br />
        <el-form-item
          label="密码"
          prop="password"
          :rules="[{ validator: validatePass, trigger: 'blur' }]"
        >
          <el-input
            style="width:20rem"
            show-password
            v-model="walletRegForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item
          label="再次输入密码"
          prop="checkPass"
          :rules="[{ validator: validatePass2, trigger: 'blur' }]"
        >
          <el-input
            style="width:20rem"
            show-password
            v-model="walletRegForm.checkPass"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <br />
        <el-form-item
          label="邮箱"
          prop="email"
          :rules="[{ required: true, message: '请输入你的游戏'},{ type:'email', message: '无效的格式'}]"
        >
          <el-input style="width:20rem" v-model="walletRegForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <br />
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="diaCancel('walletRegForm')">删除</el-button>
        <el-button type="primary" @click="regForm('walletRegForm')">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.walletRegForm.checkPass !== "") {
          this.$refs.walletRegForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.walletRegForm.password) {
        callback(new Error("两次密码不一致，请重新输入"));
      } else {
        callback();
      }
    };
    var validatePass3 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.passwordForm.checkPass !== "") {
          this.$refs.passwordForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass4 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.passwordForm.password) {
        callback(new Error("两次密码不一致，请重新输入"));
      } else {
        callback();
      }
    };
    return {
      emptyImage: require("../../../assets/" +
          "empty-wallet.jpeg"),
      emptyShow: true,
      mainShow: false,
      time: "",
      visible: false,
      visible1: false,
      tableData: [],
      table: [],
      currentPage: 1, //默认页码为1
      pagesize: 3, //默认一页显示11条
      dialogVisible: false,
      dialogWithdraw: false,
      dialogAccount: false,
      validatePass: validatePass,
      validatePass2: validatePass2,
      validatePass3: validatePass3,
      validatePass4: validatePass4,
      Withdraw_money: "",
      name: "",
      money: "",
      password: "",
      passwordForm: {
        password: "",
        checkPass: ""
      },
      walletRegForm: {
        name: "",
        password: "",
        checkPass: "",
        email: ""
      }
    };
  },
  mounted() {
    this.$post("/wal/getroleid", {
      user_id: sessionStorage.getItem("user_id")
    }).then(res => {
      if (res.message == "1" || res.message == "0") {
        this.checkWallet();
        this.getRecord();
      } else {
        this.$message.warning("没有权限");
      }
    });
  },
  methods: {
    handleSizeChange(size) {
      //一页显示多少条
      this.pagesize = size;
    },
    handleCurrentChange(currentPage) {
      //页码更改方法
      this.currentPage = currentPage;
    },
    search() {
      let timelist = [];
      if (!this.time) {
        timelist = ["1900-01-01", "2200-01-01"];
      } else {
        timelist = this.time;
      }
      this.tableData = this.table.filter(
        e =>
          timelist[0] <= e.time.slice(0, 10) &&
          e.time.slice(0, 10) <= timelist[1]
      );
    },
    checkWallet() {
      this.$post("/wal/getWallet", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        if (res.code == 504) {
          this.$message.warning("你的钱包还没有激活");
          this.emptyShow = true;
          this.mainShow = false;
          return;
        }
        if (res.code === 200) {
          this.$message.success("获取钱包信息成功!");
          this.name = res.message;
          this.$post("/wal/getAvailable_money", {
            user_id: sessionStorage.getItem("user_id")
          }).then(res => {
            this.money = res.message;
            this.emptyShow = false;
            this.mainShow = true;
          });
        }
      });
    },
    getRecord() {
      this.tableData = [];
      this.table = [];
      this.$post("/wal/getRecord", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        for (var i = 0; i < res.data.WalletTransactionRecord.length; i++) {
          var date =
            res.data.WalletTransactionRecord[i].create_time.slice(0, 10) +
            " " +
            res.data.WalletTransactionRecord[i].create_time.slice(11, 19);
          console.log(res.data.WalletTransactionRecord[i].create_time)
          var st;
          if (res.data.WalletTransactionRecord[i].status == 1) {
            st = "Applying";
          } else if (res.data.WalletTransactionRecord[i].status == 2) {
            st = "Completed";
          } else if (res.data.WalletTransactionRecord[i].status == 0) {
            st = "Failed";
          }
          this.table.unshift({
            num: res.data.WalletTransactionRecord[i].transaction_id,
            amount: res.data.WalletTransactionRecord[i].account_name,
            money: res.data.WalletTransactionRecord[i].transaction_money,
            time: date,
            state: st
          });
          this.tableData.unshift({
            num: res.data.WalletTransactionRecord[i].transaction_id,
            amount: res.data.WalletTransactionRecord[i].account_name,
            money: res.data.WalletTransactionRecord[i].transaction_money,
            time: date,
            state: st
          });
        }
      });
    },

    WithdrawPass() {
      this.Withdraw_money = ''
      var pass;
      this.$post("/wal/getPassword", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        pass = res.message;
        if (this.password != pass) {
          this.$message.warning("密码错误.");
          return;
        }
        this.dialogWithdraw = true;
        this.visible1 = false;
      });
    },

    AccountPass() {
      this.passwordForm={
        password: "",
        checkPass: ""
      }
      var pass;
      this.$post("/wal/getPassword", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        pass = res.message;
        if (this.password != pass) {
          this.$message.warning("密码错误.");
          return;
        }
        this.dialogAccount = true;
        this.visible = false;
      });
    },
    passwordSubForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$post("/wal/updatePassword", {
            user_id: sessionStorage.getItem("user_id"),
            password: this.passwordForm.password
          }).then(res => {
            if (res.code == 200) {
              this.$message.success("密码更改成功!");
              this.dialogAccount = false;
            }
          });
        } else {
          return false;
        }
      });
    },
    regForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$post("/wal/activate", {
            user_id: sessionStorage.getItem("user_id"),
            account_name: this.walletRegForm.name,
            password: this.walletRegForm.password
          }).then(res => {
            if (res.code == 504) {
              this.$message.warning("激活失败");
              this.dialogVisible = false;
              this.emptyShow = true;
              this.mainShow = false;
              return;
            }
            if (res.code == 200) {
              this.$message.success("激活成功");
              this.name = this.walletRegForm.name;
              this.money = 0;
              this.dialogVisible = false;
              this.emptyShow = false;
              this.mainShow = true;
            }
          });
        } else {
          return false;
        }
      });
    },
    diaCancel(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false;
      this.dialogAccount = false;
    },
    Withdraw() {

      if(this.Withdraw_money <= 0 || isNaN(this.Withdraw_money)){
        this.$message.warning("请输入正确的金额")
        return
      }
      var pass;
      this.$post("/wal/getPassword", {
        user_id: sessionStorage.getItem("user_id")
      }).then(res => {
        pass = res.message;
        this.$post("/wal/withdraw", {
          user_id: sessionStorage.getItem("user_id"),
          withdraw_money: this.Withdraw_money,
          password: pass
        }).then(res => {
          if (res.code == 200) {
            this.$message.success(
              "提现申请完成，请等待审核."
            );
          } else if (res.code == 504) {
            if (res.message == "Not sufficient funds") {
              this.$message.warning("没有足够的余额");
            } else {
              this.$message.warning("提现失败");
            }
          }
          this.dialogWithdraw = false;
          this.getRecord();
        });
      });
    }
  }
};
</script>

<style scoped>
.empty-box {
  height: 40rem;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
}
.main-box-top {
  margin-top: 2rem;
}
.bank-card {
  width: 32.3rem;
  height: 20rem;
  background-image: url("../../../assets/card.jpeg");
  background-size: contain;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}
.account {
  color: white;
  font-size: 22px;
  margin-left: 3rem;
  font-weight: bold;
  height: 3rem;
}
.card-div {
  width: 50rem;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.btn-div {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  height: 20rem;
}
.table {
  margin-top: 2rem;
}
.password {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
